/**
 * Copyright 2014 lerry
 * 
 * All right reserved.
 * 
 * Dec 22, 2014
 */
package com.bac.bacplatform;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.bac.javabeans.GasolineAccount;
import com.bac.javabeans.GasolineAccountInfo;
import com.bac.utils.Config;
import com.bac.utils.Storage;
import com.bac.utils.Util;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * 我的惠加油
 * 
 * @author lerry
 * 
 */
public class PersonalCouponActivity extends BaseActivity implements
		OnClickListener {

	private ArrayList<GasolineAccountInfo> mGasolineAccountInfos;

	private ArrayList<GasolineAccount> mGasolineAccountList;

	private OneCardAdapter mCardsAdapter;

	private ViewPager mViewPager;

	private int mCurrentIndex = 0;

	private Button mBtGoing, mBtOver;

	private ListView mListViewCards;

	private boolean mIsFinish = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.personal_coupon);

		// 使用notifyDataSetChanged来更新listview，这个数据的引用必须是同一个，否者刷新没有效果
		mGasolineAccountList = new ArrayList<GasolineAccount>();
		findViewById(R.id.go_now).setOnClickListener(this);
		findViewById(R.id.title_left).setOnClickListener(this);
		checkAccount();
	}

	@Override
	public void init() {
//		checkAccount();
	}

	public void checkAccount() {

		/**
		 * 成功返回结果
		 */
		Listener<String> sL = new Response.Listener<String>() {
			@Override
			public void onResponse(String response) {
				Log.i("PersonalCouponActivity----success", "response---"
						+ response.toString());
				HashMap<String, String> result = new Gson().fromJson(
						response.toString(),
						new TypeToken<HashMap<String, String>>() {
						}.getType());
				if (result != null && result.containsKey("count")) {
					if (Integer.valueOf(result.get("count")) > 0) {
						setContentView(R.layout.my_coupon);
						findViewById(R.id.title_left1).setOnClickListener(
								new View.OnClickListener() {
									@Override
									public void onClick(View v) {
										finishActivityOut();
									}
								});
						mBtGoing = (Button) findViewById(R.id.bt_going);
						mBtGoing.setOnClickListener(PersonalCouponActivity.this);
						mBtOver = (Button) findViewById(R.id.bt_over);
						mBtOver.setOnClickListener(PersonalCouponActivity.this);
						initListViewCards();
						getGasonlineStatistic();
					} else {
						dismissLoadingProgressNow();
						findViewById(R.id.go_now).setVisibility(View.VISIBLE);
						findViewById(R.id.tv_no_buy)
								.setVisibility(View.VISIBLE);
					}
				}
			}
		};

		showLoadingProgress();
		String path = Config.URL_COUPON_COUNT;
		Util.httpRequestToGet(path, sL, this);

	}

	/**
	 * 获取已订购套餐
	 * 
	 * @param type
	 *            0已结束，1正在进行
	 */
	public void getGasonlineStatistic() {
		/**
		 * 成功返回结果
		 */
		Listener<String> sL = new Response.Listener<String>() {
			@Override
			public void onResponse(String response) {
				dismissLoadingProgress();
				Log.i("PersonalCouponActivity----success", "response---"
						+ response.toString());
				if (response.toString().equals("[]")) {
					Log.e("PersonalCouponActivity----",
							"have no account!!!!!!!!");
					// findViewById(R.id.ly_content).setVisibility(View.VISIBLE);
					return;
				}

				Type listType = new TypeToken<ArrayList<GasolineAccountInfo>>() {
				}.getType();
				Gson gson = new Gson();
				mGasolineAccountInfos = gson.fromJson(response, listType);
				initViewPager();
				setAdapterListData();
			}
		};

		String path = Config.URL_COUPON_STATISTIC;
		Map<String, String> map = new HashMap<String, String>();
		Util.httpRequestToGetWithParams(path, sL, this, map);

	}

	public void initViewPager() {
		mViewPager = (ViewPager) findViewById(R.id.view_pager);

		findViewById(R.id.ly_previous).setOnClickListener(this);
		findViewById(R.id.ly_next).setOnClickListener(this);

		mViewPager.setAdapter(new MyPagerApapter());
		mViewPager.setOnPageChangeListener(new MyPageChangeListener());

		if (mGasolineAccountInfos.size() > 1) {
			findViewById(R.id.ly_previous).setEnabled(false);
			findViewById(R.id.ly_next).setEnabled(true);
			((ImageView) findViewById(R.id.img_previous))
					.setImageResource(R.drawable.profile_bg_previous_gray);
			((TextView) findViewById(R.id.tv_previous))
					.setTextColor(0xffcfcfcf);
			((ImageView) findViewById(R.id.img_next))
					.setImageResource(R.drawable.profile_bg_next_normal);
			((TextView) findViewById(R.id.tv_next)).setTextColor(0xff4dadde);
		} else {
			findViewById(R.id.ly_previous).setEnabled(false);
			findViewById(R.id.ly_next).setEnabled(false);
			((ImageView) findViewById(R.id.img_previous))
					.setImageResource(R.drawable.profile_bg_previous_gray);
			((TextView) findViewById(R.id.tv_previous))
					.setTextColor(0xffcfcfcf);
			((ImageView) findViewById(R.id.img_next))
					.setImageResource(R.drawable.profile_bg_next_gray);
			((TextView) findViewById(R.id.tv_next)).setTextColor(0xff4dadde);
		}

	}

	public void initListViewCards() {
		mListViewCards = (ListView) findViewById(R.id.list_cards);
		mCardsAdapter = new OneCardAdapter(getApplicationContext(),
				mGasolineAccountList);
		mListViewCards.setAdapter(mCardsAdapter);

		mListViewCards.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Log.i("item click", ""
						+ mGasolineAccountList.get(position).getId());
				Intent intent = new Intent(PersonalCouponActivity.this, CouponDetailActivity.class);
				intent.putExtra("id", ""+mGasolineAccountList.get(position).getId());
				startActivityIn(intent);
			}
		});
	}

	public void setAdapterListData() {
		mGasolineAccountList.clear();
		ArrayList<GasolineAccount> tmp = (ArrayList<GasolineAccount>) mGasolineAccountInfos
				.get(mCurrentIndex).getUnFinishedAccounts();
		mGasolineAccountList.addAll(tmp);
		mCardsAdapter.notifyDataSetChanged();
	}

	class OneCardAdapter extends BaseAdapter {
		private ArrayList<GasolineAccount> mAccountList;
		private Context mContext;

		public OneCardAdapter(Context context,
				ArrayList<GasolineAccount> arrayList) {
			mAccountList = arrayList;
			mContext = context;
		}

		@Override
		public int getCount() {
			return mAccountList.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			GasolineAccount gasolineAccount = mAccountList.get(position);
			final ViewHolder viewHolder;

			if (convertView == null) {
				convertView = LayoutInflater.from(mContext).inflate(
						R.layout.coupon_card_item, null);

				viewHolder = new ViewHolder();

				viewHolder.cardnameTV = (TextView) convertView
						.findViewById(R.id.tv_coupon_item);

				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			
			// 充值的条目
			String info = String.format(
					getString(R.string.recharge_text), gasolineAccount.getStartDate(),
					""
							+ (gasolineAccount.getPrincipal() * gasolineAccount
									.getPredeterminedCycle()), ""
							+ gasolineAccount.getPredeterminedCycle());
			viewHolder.cardnameTV.setText(info);

			return convertView;
		}

		class ViewHolder {
			TextView cardnameTV;
			ImageView divider;
		}

	}

	class MyPagerApapter extends PagerAdapter {

		@Override
		public int getCount() {
			return mGasolineAccountInfos.size();
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}

		@SuppressLint("NewApi")
		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
			RelativeLayout relativeLayout = new RelativeLayout(
					getApplicationContext());
			relativeLayout.setLayoutParams(params);

			RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
			TextView cardTextView = new TextView(getApplicationContext());
			cardTextView.setGravity(Gravity.CENTER_HORIZONTAL);
			cardTextView.setId(1000);
			cardTextView.setText(mGasolineAccountInfos.get(position)
					.getCardNo());
			cardTextView.setTextColor(0xff666666);
			cardTextView.setTextSize(18);
			cardTextView.setLayoutParams(params1);

			RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			params2.addRule(RelativeLayout.BELOW, cardTextView.getId());
			params2.addRule(RelativeLayout.CENTER_HORIZONTAL);
			params2.topMargin = 5;
			TextView nameTextView = new TextView(getApplicationContext());
			nameTextView.setId(10001);
			nameTextView.setGravity(Gravity.CENTER_HORIZONTAL);
			nameTextView.setText(mGasolineAccountInfos.get(position)
					.getCardName());
			nameTextView.setTextColor(0xff666666);
			nameTextView.setTextSize(18);
			nameTextView.setLayoutParams(params2);

			RelativeLayout.LayoutParams params3 = new RelativeLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			params3.addRule(RelativeLayout.BELOW, cardTextView.getId());
			params3.addRule(RelativeLayout.RIGHT_OF, nameTextView.getId());
			params3.addRule(RelativeLayout.ALIGN_BOTTOM, nameTextView.getId());
			ImageView iconImage = new ImageView(getApplicationContext());
			iconImage.setImageResource(R.drawable.profile_bg_hui);
			iconImage.setLayoutParams(params3);

			relativeLayout.addView(cardTextView);
			relativeLayout.addView(nameTextView);
			relativeLayout.addView(iconImage);
			container.addView(relativeLayout, params);

			return relativeLayout;
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

	}

	class MyPageChangeListener implements OnPageChangeListener {

		@Override
		public void onPageScrollStateChanged(int arg0) {

		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}

		@Override
		public void onPageSelected(int position) {
			Log.i("MyPageChangeListener--", "mCurrentIndex--" + mCurrentIndex);
			Log.i("MyPageChangeListener--", "position--" + position);
			if (position == 0) {
				findViewById(R.id.ly_previous).setEnabled(false);
				findViewById(R.id.ly_next).setEnabled(true);
				((ImageView) findViewById(R.id.img_previous))
						.setImageResource(R.drawable.profile_bg_previous_gray);
				((TextView) findViewById(R.id.tv_previous))
						.setTextColor(0xffcfcfcf);
				((ImageView) findViewById(R.id.img_next))
						.setImageResource(R.drawable.profile_bg_next_normal);
				((TextView) findViewById(R.id.tv_next))
						.setTextColor(0xff4dadde);
			} else if (position == mGasolineAccountInfos.size() - 1) {
				findViewById(R.id.ly_previous).setEnabled(true);
				findViewById(R.id.ly_next).setEnabled(false);
				((ImageView) findViewById(R.id.img_previous))
						.setImageResource(R.drawable.profile_bg_previous_normal);
				((TextView) findViewById(R.id.tv_previous))
						.setTextColor(0xff4dadde);
				((ImageView) findViewById(R.id.img_next))
						.setImageResource(R.drawable.profile_bg_next_gray);
				((TextView) findViewById(R.id.tv_next))
						.setTextColor(0xffcfcfcf);
			} else if (0 < position
					&& position < mGasolineAccountInfos.size() - 1) {
				findViewById(R.id.ly_previous).setEnabled(true);
				findViewById(R.id.ly_next).setEnabled(true);
				((ImageView) findViewById(R.id.img_previous))
						.setImageResource(R.drawable.profile_bg_previous_normal);
				((TextView) findViewById(R.id.tv_previous))
						.setTextColor(0xff4dadde);
				((ImageView) findViewById(R.id.img_next))
						.setImageResource(R.drawable.profile_bg_next_normal);
				((TextView) findViewById(R.id.tv_next))
						.setTextColor(0xff4dadde);
			}
			ArrayList<GasolineAccount> tepList = (ArrayList<GasolineAccount>) mGasolineAccountInfos
					.get(position).getUnFinishedAccounts();
			if (mIsFinish) {
				tepList = (ArrayList<GasolineAccount>) mGasolineAccountInfos
						.get(position).getFinishedAccounts();
			}
			mGasolineAccountList.clear();
			mGasolineAccountList.addAll(tepList);
			mCardsAdapter.notifyDataSetChanged();
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_left:
			finishActivityOut();
			break;
		case R.id.go_now:
			// Intent intentToCoupon = new Intent(this,
			// BuyCouponActivity.class);
			// startActivityIn(intentToCoupon);
			Intent intentToBuy = new Intent(this, KeyToOilActivity.class);
			startActivityIn(intentToBuy);
			break;
		case R.id.ly_previous:
			mCurrentIndex--;
			if (mCurrentIndex < 0) {
				mCurrentIndex = 0;
			}
			Log.i("pre--click", "mCurrentIndex---" + mCurrentIndex);
			mViewPager.setCurrentItem(mCurrentIndex, true);
			break;
		case R.id.ly_next:
			mCurrentIndex++;
			if (mCurrentIndex > mGasolineAccountInfos.size() - 1) {
				mCurrentIndex = mGasolineAccountInfos.size() - 1;
			}
			Log.i("next--click", "mCurrentIndex---" + mCurrentIndex);
			mViewPager.setCurrentItem(mCurrentIndex, true);
			break;
		case R.id.bt_going:
			selectButton(R.id.bt_going);
			break;
		case R.id.bt_over:
			selectButton(R.id.bt_over);
			break;
		default:
			break;
		}
	}

	public void selectButton(int id) {
		mBtGoing.setBackgroundResource(R.drawable.profile_tab_in_normal);
		mBtGoing.setTextColor(0xff666666);
		mBtOver.setBackgroundResource(R.drawable.profile_tab_end_normal);
		mBtOver.setTextColor(0xff666666);
		if (id == R.id.bt_going) {
			mBtGoing.setBackgroundResource(R.drawable.profile_tab_in_focus);
			mBtGoing.setTextColor(0xffffffff);
			mIsFinish = false;
		} else {
			mBtOver.setBackgroundResource(R.drawable.profile_tab_end_focus);
			mBtOver.setTextColor(0xffffffff);
			mIsFinish = true;
		}
		changeList(mIsFinish);
	}

	/**
	 * 切换进行中和已结束
	 * 
	 * @param isFinish
	 *            是否进行中
	 */
	public void changeList(boolean isFinish) {
		if (isFinish) {
			mGasolineAccountList.clear();
			ArrayList<GasolineAccount> tmp = (ArrayList<GasolineAccount>) mGasolineAccountInfos
					.get(mCurrentIndex).getFinishedAccounts();
			mGasolineAccountList.addAll(tmp);
			mCardsAdapter.notifyDataSetChanged();
		} else {
			mGasolineAccountList.clear();
			ArrayList<GasolineAccount> tmp = (ArrayList<GasolineAccount>) mGasolineAccountInfos
					.get(mCurrentIndex).getUnFinishedAccounts();
			mGasolineAccountList.addAll(tmp);
			mCardsAdapter.notifyDataSetChanged();
		}
	}
}
